package com.vancouver.knows.ui.activity.citynews;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLayoutChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.vancouver.knows.R;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.citynews.CityNewsCommentsPullControllerView;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.CommentInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.UserInsertCommentTaskMark;

/**
 * 评论列表
 * 
 * @author chenxunlin01
 * 
 */
public class CityNewsCommentsActivity extends BaseActivity implements IResultReceiver, OnLayoutChangeListener, View.OnClickListener {

	public static final int NEW_COMMENT_REQUEST = 305;

	public static final String NEW_COMMENT_COUNT_EXTRA = "new_comment_count_extra";

	@Bind(R.id.commentContent)
	EditText commentContent;
	@Bind(R.id.toolbar)
	Toolbar toolbar;
	@Bind(R.id.toobarTitle)
	TextView toobarTitle;
	@Bind(R.id.detailContentLayout)
	LinearLayout detailContentLayout;
	@Bind(R.id.commentsControllerView)
	CityNewsCommentsPullControllerView commentsControllerView;
	@Bind(R.id.commentContentLayout)
	LinearLayout commentContentLayout;
	@Bind(R.id.commentBtn)
	TextView commentBtn;

	private BusinessModule bModule;
	private String postId;
	private int newCommentCount = 0;

	// 软件盘弹起后所占高度阀值
	private int keyHeight = 0;
	private boolean editTextShow = false;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_citynews_comments);
		bModule = imContext.getBusinessModule();

		if (imContext.getSharedPrefManager().getUserId() == null) {
			commentContent.setFocusable(false);
			commentContent.setOnClickListener(this);
		}

		dialog = new ProgressDialog(this, R.style.MyAlertDialogStyle);
		dialog.setTitle("");
		dialog.setMessage(getResources().getString(R.string.report_loading));
		dialog.setIndeterminate(false);
		dialog.setCancelable(true);
		
		Intent intent = getIntent();
		if (intent == null) {
			return;
		}

		postId = intent.getStringExtra("postId");
		if (StringUtil.isEmptyString(postId)) {
			return;
		}

		toolbar.setTitle("");
		toobarTitle.setText(R.string.comment_title);
		setSupportActionBar(toolbar);
		toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back));

		init();

		// 获取屏幕高度
		int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
		// 阀值设置为屏幕高度的1/3
		keyHeight = screenHeight / 3;
		// 添加layout大小发生改变监听器
		detailContentLayout.addOnLayoutChangeListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (imContext.getSharedPrefManager().getUserId() != null) {
			commentContent.setFocusableInTouchMode(true);
			commentContent.setOnClickListener(null);
		} else {
			commentContent.setFocusable(false);
			commentContent.setOnClickListener(this);
		}
	}

	private void init() {
		commentsControllerView.loadData(postId);

		String author = getIntent().getStringExtra("comment_author");
		String commentId = getIntent().getStringExtra("comment_id");
		if(!StringUtil.isEmptyString(commentId) && !StringUtil.isEmptyString(author)){
			commentContent.setText("@" + author + " ");
			CommentInfo commentInfo = new CommentInfo();
			commentInfo.setId(commentId);
			commentInfo.setAuthor(author);
			commentContent.setTag(commentInfo);
			commentContent.setSelection(commentContent.getText().toString().length());
			commentContent.setFocusable(true);
			commentContent.setFocusableInTouchMode(true);
			commentContent.requestFocus();
			InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
					Context.INPUT_METHOD_SERVICE);
			inputManager.showSoftInput(commentContent, 0);
		} else {
			commentContent.setText("");
		}
	}

	private void postComment() {
		String contentStr = commentContent.getText().toString().trim();
		if (StringUtil.isEmptyString(contentStr)) {
			return;
		}

		CommentInfo commentInfo = (CommentInfo) commentContent.getTag();
		String commentParentId = "";
		if (commentInfo != null) {
			if (contentStr.contains("@" + commentInfo.getAuthor())) {
				commentParentId = commentInfo.getId();
			}
		}
		userInsertComment(contentStr, commentParentId);
	}

	@OnClick(R.id.commentBtn)
	public void onCommentBtnClick() {
		if (editTextShow) {
			postComment();
		}
	}

	private void updateCommentBtn() {
		if (editTextShow) {
			commentBtn.setText(R.string.right_btn);
			commentBtn.setTextColor(getResources().getColor(R.color.orange));
		} else {
			commentBtn.setText("");
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void userInsertComment(String contentStr, String commentParentId) {
		if (!AppUtils.getLoginStatus(this)) {
			return;
		}
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		UserInsertCommentTaskMark aTaskMark = bModule.getTaskMarkPool().createUserInsertCommentTaskMark(postId,
				contentStr, commentParentId);
		bModule.getServiceWrapper().userInsertComment(this, aTaskMark, userInfo.getUserID(), postId, contentStr,
				commentParentId);
		InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(commentContent.getWindowToken(), 0);
		dialog.show();
	}

	public void userInsertParentComment(CommentInfo parentCommentInfo) {
		commentContent.setText("");
		commentContent.setText("@" + parentCommentInfo.getAuthor() + " " + commentContent.getText().toString());
		commentContent.setTag(parentCommentInfo);
		commentContent.setSelection(commentContent.getText().toString().length());
		commentContent.setFocusable(true);
		commentContent.setFocusableInTouchMode(true);
		commentContent.requestFocus();
		InputMethodManager inputManager = (InputMethodManager) commentContent.getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(commentContent, 0);
	}

	@Override
	public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
			int oldBottom) {
		if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
			editTextShow = true;
			updateCommentBtn();

		} else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
			editTextShow = false;
			updateCommentBtn();
		}
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		if (taskMark instanceof UserInsertCommentTaskMark) {
			if(taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR){
				dialog.hide();
				Toast.makeText(this, R.string.report_error, 200).show();
				
			}else if(taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER){
				commentContent.setText("");
				commentsControllerView.flush();
				dialog.hide();
				newCommentCount++;
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		dialog.dismiss();
		super.onDestroy();
	}

	public void setShowCommentInput() {
		editTextShow = true;
		updateCommentBtn();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.commentContent) {
			if (!commentContent.isFocusable()) {
				startActivity(new Intent(this, LoginActivity.class));
			}
		}
	}

	@Override
	public void finish() {
		Intent intent  = new Intent();
		intent.putExtra(NEW_COMMENT_COUNT_EXTRA, newCommentCount);
		intent.putExtra("postId", postId);
		setResult(RESULT_OK, intent);
		super.finish();
	}
}
